import * as qiniu from 'qiniu-js';

/** qiniu-js@v3 */
class QiniuKodo {
  status = 0; // 0.prepare 1.processing 2.done 3.error

  constructor(compressOptions) {
    this.compressOptions = compressOptions;
  }

  async run(file, key, authToken, callback = {}) {
    if (this.status === 1) return;

    // 设置状态为处理中状态
    this.status = 1;

    // 统一回调处理
    const {
      onSuccess,
      onError
    } = callback;
    const compressTypes = [
      'image/webp',
      'image/jpeg',
      'image/png',
      'image/bmp'
    ];

    if (this.compressOptions && compressTypes.includes(file.type)) {
      file = await qiniu.compressImage(file, this.compressOptions).then(data => data.dist)
    }

    const observable = qiniu.upload(file, key, authToken);
    const observer = {
      complete: (response) => {
        this.status = 2;

        if (onSuccess) onSuccess(response);
      },
      error: (info) => {
        this.status = 3;

        // error code => https://developer.qiniu.com/kodo/3928/error-responses
        if (onError) onError(info);
      }
    };

    this.subscription = observable.subscribe(observer);
  }
  
  abort () {
    if (this.subscription) {
      this.subscription.unsubscribe();
      this.status = 0;
    }
  }
}

export default QiniuKodo;